package jdos.hardware;

import jdos.Dosbox;
import jdos.gui.Main;
import jdos.gui.Render;
import jdos.misc.Log;
import jdos.types.LogSeverities;
import jdos.types.LogTypes;

public class VGA_dac {

    static int pel_index;
    static int write_index;

    static private IoHandler.IO_WriteHandler write_p3c8 = new IoHandler.IO_WriteHandler() {
        public void call(/*Bitu*/int port, /*Bitu*/int val, /*Bitu*/int iolen) {
            write_index=(short)(val & 0xFF);
            pel_index=0;
        }
    };

    static public /*Bitu*/int GFX_GetRGB(/*Bit8u*/int red,/*Bit8u*/int green,/*Bit8u*/int blue) {
		return ((blue << 0) | (green << 8) | (red << 16)) | (255 << 24);	
    }

    static int red;
    static int green;
    static int blue;
    static private IoHandler.IO_WriteHandler write_p3c9 = new IoHandler.IO_WriteHandler() {
        public void call(/*Bitu*/int port, /*Bitu*/int val, /*Bitu*/int iolen) {
            val&=0x3f;
            switch (pel_index) {
            case 0:
                //VGA.vga.dac.rgb[VGA.vga.dac.write_index].red=(short)val;
                red=val;
                pel_index=1;
                break;
            case 1:
                //VGA.vga.dac.rgb[VGA.vga.dac.write_index].green=(short)val;
                green=val;
                pel_index=2;
                break;
            case 2:
                //VGA.vga.dac.rgb[VGA.vga.dac.write_index].blue=(short)val;
                blue=val;
                Main.cmap[write_index] = GFX_GetRGB((red << 2) | ( red >> 4 ), (green << 2) | ( green >> 4 ), (blue << 2) | ( blue >> 4 ));
                write_index++;write_index&=0xFF;
    //		VGA.vga.dac.read_index = VGA.vga.dac.write_index - 1;//disabled as it breaks Wari
                pel_index=0;
                break;
            default:
                Log.log(LogTypes.LOG_VGAGFX,LogSeverities.LOG_NORMAL,"VGA:DAC:Illegal Pel Index");			//If this can actually happen that will be the day
                break;
            }
        }
    };

    static public void VGA_SetupDAC() {
        pel_index=0;
        write_index=0;
        IoHandler.IO_RegisterWriteHandler(0x3c8,write_p3c8,IoHandler.IO_MB);
        IoHandler.IO_RegisterWriteHandler(0x3c9,write_p3c9,IoHandler.IO_MB);
        //}
    }
}
